package daohibernate;


import hibernate.HibernateUtil;

import java.util.List;




import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import entities.Cliente;


public class ClienteDAO {
	private static ClienteDAO instancia = null;	
	private static SessionFactory sf = null;	
	
	
	public static ClienteDAO getInstancia(){
		if(instancia == null){
			sf = HibernateUtil.getSessionFactory();
			instancia = new ClienteDAO();
		} 
		return instancia;
	}

	public void altaCliente(Cliente c){
		Session s = sf.openSession();
		s.beginTransaction();
		//System.out.println("Antes de persistir Cliente en la BD.");
		s.persist(c);
		s.flush();
		s.getTransaction().commit();
		s.close();
		System.out.println("Cliente persistido");
	}
	
	public void bajaCliente(Cliente c){
		System.out.println( "DAO BAJA");
		Session s = sf.openSession();
		Transaction tx = s.beginTransaction();
		System.out.println( "antes de s.delete(c) ");
		s.delete(c);
		System.out.println( "antes de tx.commit() ");
		tx.commit();
		s.close();	
	}
	
	public Cliente buscarCliente(String cuil){
		Session s = sf.openSession();
		@SuppressWarnings("unchecked")
		List<Cliente> clientes = s.createQuery("from Cliente where cuil = '" + cuil + "'").list();
		s.close();
		for(Cliente c : clientes){
			return c;
		}
		return null;
	}
	
	public void modificarCliente(Cliente c){
		Session s = sf.openSession();
		s.beginTransaction();
						
		s.update(c);
		System.out.println("En el dato de modif cliente");
		System.out.println(c.getCuil());
		s.flush();
		s.getTransaction().commit();
	}
	
	public void grabarClientes(List<Cliente> lista){
		Session s = sf.openSession();
		s.beginTransaction();
		for(Cliente elemento:lista){
			s.persist(elemento);
		}
		s.flush();
		s.getTransaction().commit();
	}

	
	public boolean verificarCliente(String cuil){
		
		Session s = sf.openSession();

		Query q = s.createQuery("from Cliente where cuil = '" + cuil + "'");
		q.setFirstResult(0);
		q.setMaxResults(1);

		if((Cliente)q.uniqueResult() != null){
			return true;
		}else{
			return false;
		}
	}
	
	
	

}
